package cc.ilzy.mall.coupon.interceptors;

import cc.ilzy.mall.exceptions.ExceptionEnum;
import cc.ilzy.mall.exceptions.MallException;
import cc.ilzy.mall.model.pojo.User;
import cc.ilzy.mall.utils.JWTUtils;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWTPayload;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class UserLoginInterceptor implements HandlerInterceptor {
    private static final ThreadLocal<User> userHolder = new ThreadLocal<>();

    public static User getCurrentUser() {
        return userHolder.get();
    }

    public static void setCurrentUser(User user) {
        userHolder.set(user);
    }

    public static void removeCurrentUser() {
        userHolder.remove();
    }

    /**
     * * 在请求处理之前进行拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws
            Exception {
        String accessToken = StrUtil.isBlank(request.getHeader("Authorization")) ? request.getParameter("token") : request.getHeader("Authorization");
        if (StrUtil.isBlank(accessToken)) {
            throw new MallException(ExceptionEnum.TOKEN_NOT_EXIST);
        }
        // 验证JWT
        JWTPayload jwtPayload = JWTUtils.checkJWT(accessToken);
        JSONObject claimsJson = jwtPayload.getClaimsJson();
        Long id = claimsJson.getLong("id");
        String name = claimsJson.getStr("name");
        String mail = claimsJson.getStr("mail");
        String headImg = claimsJson.getStr("headImg");

        //封装到ThreadLocal中
        User user = new User();
        user.setId(id).setName(name).setMail(mail).setHeadImg(headImg);
        userHolder.set(user);
        return true;
    }

    /**
     * * 在请求处理完成后进行拦截
     * ThreadLocal 清除中间变量，防止内存泄漏
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        userHolder.remove();
    }
}
